package sel.me.spring.boot245.web.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import sel.me.spring.boot245.web.domain.base.Result;
import sel.me.spring.boot245.web.exception.UnifyStrErrorCode;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Java 7 的编译器和运行环境支持新的 try-with-resources 语句，称为 ARM 块(Automatic Resource Management) ，自动资源管理。
 * https://blog.csdn.net/shun0304/article/details/81738243
 *
 * @author shenenlu
 * @date 2021-7-28 16:10
 */
@Slf4j
public class ResultUtil {

    public static Result<Void> resultSuccess() {
        Result<Void> result = new Result<>();
        result.setCode(UnifyStrErrorCode.SUCCESS.getErrorCode());
        result.setCode(UnifyStrErrorCode.SUCCESS.getErrorMsg());
        return result;
    }

    public static Result<Void> resultSuccess(String msg) {
        Result<Void> result = new Result<>();
        result.setCode(UnifyStrErrorCode.SUCCESS.getErrorCode());
        result.setMsg(msg);
        return result;
    }

    public static Result<Void> resultError(UnifyStrErrorCode code) {
        Result<Void> result = new Result<>();
        result.setCode(code.getErrorCode());
        result.setMsg(code.getErrorMsg());
        return result;
    }

    public static Result<Void> resultError(UnifyStrErrorCode code, String msg) {
        Result<Void> result = new Result<>();
        result.setCode(code.getErrorCode());
        result.setMsg(msg);
        return result;
    }

    public static void responseJson(HttpServletResponse response, Object object) {
        try (PrintWriter printWriter = response.getWriter()) {
            response.setStatus(200);
            printWriter.print(JSON.toJSONString(object));
            printWriter.flush();
        } catch (IOException e) {
            log.error("ResultUtil.responseJson, object={}, e={}", object, e);
        }
    }


}
